<template>
  <div>
    <div class="search">
      <input
        class="search-input"
        v-model="keyword"
        type="text"
        placeholder="输入城市名或拼音"
        style="outline:none;border:0;"
      />
    </div>
    <div class="search-content" ref="search" v-show="this.keyword">
      <ul>
        <li
          v-for="item of list"
          :key="item.id"
          class="search-item"
          @click="handleCityClick(item.name)"
        >{{item.name}}</li>
        <li class="search-item" v-show="hasNoData">没有找到匹配数据</li>
      </ul>
    </div>
  </div>
</template>
<script>
import Bscroll from "better-scroll"
export default {
  name: 'citySearch',
  data() {
    return {
      keyword: '',
      list: [],
      timer: null
    }
  },
  props: {
    cities: Object
  },
  computed:{      //计算是否有list,没的话显示“没有找到匹配数据”
      hasNoData(){
          return !this.list.length
      }
  },
  methods:{
    handleCityClick(city){
       this.$store.commit('changeCity',city)
              this.$router.push('/')
    }
  },
  watch: {
    keyword() {
      if (this.timer) {            // 函数节流
        clearTimeout(this.timer)
      }     
      if(!this.keyword){
          this.list=[]
          return
      }                       
      this.timer = setTimeout(() => {
        const result = []
        for (let i in this.cities) {   //循环检测输入的值是否在cities的i里，在的话把element放在this.list里
          this.cities[i].forEach(element => {
            if (element.name.indexOf(this.keyword) > -1 || element.spell.indexOf(this.keyword) > -1) {
              result.push(element)
            }
          });
          this.list = result
        }
      }, 100)
    }
  },
  mounted(){
     this.scroll= new Bscroll(this.$refs.search)
  }
}
</script>
<style lang="stylus" scoped>
@import '~styles/varibles.styl';

.search {
  height: 0.72rem;
  padding: 0.1rem;
  background: $bgColor;

  .search-input {
    box-sizing: border-box;
    width: 100%;
    outline: none;
    outline-style: none;
    height: 0.62rem;
    line-height: 0.62rem;
    text-align: center;
    padding: 0 0.1rem;
    border-radius: 0.06rem;
    color: #666;
  }
}

.search-content 
  overflow: hidden;
  z-index: 1;
  position: absolute;
  top: 1.66rem;
  left: 0;
  right: 0;
  bottom: 0;
  background #eee
  .search-item
    line-height .62rem
    color:#666
    background #fff
    border-bottom:0.01rem solid #ccc;
    padding-left:.2rem;

</style>

